export class EventEmitter {
	private eventCallback: any = {};
	/**
	 * 添加事件
	 * @param event 事件名称，字符串
	 * @param cb 事件回调函数
	 * @returns EventEmitter
	 */
	public on(event: string, cb: (...arg: any[]) => void): EventEmitter {
		const callbackList = this.eventCallback[event] || [];
		callbackList.push(cb);
		this.eventCallback[event] = callbackList;
		return this;
	}

	/**
	 * 取消监听事件
	 * @param event 事件名称
	 * @param cb 事件回调函数,不传则取消所有
	 * @returns
	 */
	public off(event: string, cb?: any) {
		if (!cb) {
			this.eventCallback[event] = [];
			return this;
		}
		const callbackList = this.eventCallback[event] || [];
		this.eventCallback[event] = callbackList.filter((fn: any) => fn !== cb);
		return this;
	}

	/**
	 * 发送事件
	 * @param event 事件名称，字符串
	 * @param args 触发时间传递的参数
	 * @returns
	 */
	public emit(event: string, ...args: any[]): EventEmitter {
		const callbackList = this.eventCallback[event] || [];
		callbackList.forEach((fn: (...arg: any) => void) => {
			fn(...args);
		});
		return this;
	}

	/**
	 * 仅触发一次事件，执行完后自动去掉监听
	 * @param event 事件名称
	 * @param cb 回调函数
	 * @returns
	 */
	public once(event: string, cb: (...arg: any[]) => void) {
		// 封装一个单次执行函数
		const fn = (...args: any[]) => {
			cb.apply(this, args);
			this.off(event, fn);
		};
		this.on(event, fn);
		return this;
	}
}
